package it.intecs.pisa.smarcos.activities;

import it.intecs.pisa.smarcos.R;
import it.intecs.pisa.smarcos.base.BeepManager;
import it.intecs.pisa.smarcos.base.GestureEvents;
import it.intecs.pisa.smarcos.base.GestureIntents;
import it.intecs.pisa.smarcos.base.Lists;
import it.intecs.pisa.smarcos.base.SpeechManager;
import it.intecs.pisa.smarcos.util.MathUtils;

import java.util.ArrayList;

import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Vibrator;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


public class SearchContactByScroll extends BaseActivity {

	public static final String INTENT_SHOW="it.intecs.pisa.smarcos.activities.SearchContact.SHOW";
	private static final String TAG = SearchContactByScroll.class.getSimpleName();
	// Request code for the contact picker activity

	private SpeechManager speechManager;
	private BeepManager beepManager;
	
	View view; 
	Lists list;
	private Context context;
	private Vibrator vibrator;
	private ViewGroup baseCenterView;
	private String position;
	LayoutInflater inflater;
	protected Cursor contactCursor=null;
	private TextView contactName; 
	private TextView contactNumber; 

	private String number;
	private String name;
	private ArrayList<String> contactsIdArray = new ArrayList<String>();
	private ArrayList<String> contactsNameArray = new ArrayList<String>();
	private ArrayList<String> contactsNumberArray = new ArrayList<String>();
	private int counter = 0;
	private int totalContacts = 0;
	
	float startX,startY;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Log.d(TAG, "OnCreate");

		context = getApplicationContext();
		speechManager = SpeechManager.getInstance(context);
		vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
		beepManager = BeepManager.getInstance(getApplicationContext());

		RetrieveContacts();
		if (totalContacts == 0){
			speechManager.say(R.string.TTS_Menu_Contact_No);
			onClick_A();
		}	
		// Metodo di BaseViewManager
		Init(getBaseContext());
		inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 		
		setContentView(getBaseView());

		view = inflater.inflate(R.layout.scroll_contacts, null);

		baseCenterView = (ViewGroup) findViewById(R.id.center_base_view);
		baseCenterView.addView(view);
		contactName = (TextView) findViewById(R.id.ContactName);
		contactNumber = (TextView) findViewById(R.id.ContactNumber);

		position = getString(R.string.MV_Contacts_Voice);

		list = new Lists(totalContacts, beepManager);
	}



	@Override
	public void onResume() {
		super.onResume();

		speechManager.say(R.string.TTS_Contact_Swipe);
	}

	@Override
	public void onPause() {
		super.onPause();
		Log.d(TAG, "OnPause");	
	}

	// CLOSE - BACK
	@Override
	public void onClick_A(){
		Log.d(TAG, "onClick_A");

		Intent returnIntent;
		returnIntent=new Intent("it.intecs.pisa.smarcos.services.ResultReceiver.SHOW");
		returnIntent.putExtra("Result", "NORESULT");
		returnIntent.addCategory(Intent.CATEGORY_DEFAULT);					
		sendBroadcast(returnIntent);
		sentResult = true;
		vibrator.vibrate(300);
		finish();
	}

	// POSITION
	@Override
	public void onClick_B(){
		Log.d(TAG, "onClick_B");
		if(position != null)
			speechManager.say(position, false, false);	
	}

	// REPEAT
	@Override
	public void onClick_C(){
		
		Log.d(TAG, "onClick_C");
		speechManager.say(name, true, false);
		speechManager.say(number, true, false);
	}

	// DONE 
	@Override
	public void onClick_D(){
		Log.d(TAG, "onClick_D");
		Intent returnIntent;
		returnIntent=new Intent("it.intecs.pisa.smarcos.services.ResultReceiver.SHOW");
		returnIntent.putExtra("Result", number);
		returnIntent.addCategory(Intent.CATEGORY_DEFAULT);					
		sendBroadcast(returnIntent);
		sentResult = true;
		vibrator.vibrate(300);
		finish();
	}


	@Override
	public void onClick_Center(int event, float X, float Y){
		Log.d(TAG, "onClick_Center");
		
		float lenghtTreshold=10;
		
		switch(event)
		{
			case GestureEvents.ONFLING_START:

				startX = X;
				startY = Y;
				break;

			case GestureEvents.ONFLING_STOP:

				float endX,endY;

				endX = X;
				endY = Y;

				float gestureLenght=0;

				gestureLenght=MathUtils.distanceBetweenPoints(endX,startX,endY,startY);

				if(gestureLenght>lenghtTreshold){

					String gesture = MathUtils.calculateSlice(endX,startX,endY,startY);
					if (gesture.length() != 0)
						ContactsGestureHandling(gesture);
				}
				break;

			case GestureEvents.ONDOUBLETAP:
				ContactsGestureHandling(GestureIntents.INTENT_GESTURE_SELECT);
				break;
		}
		
	}

	private void RetrieveContacts() {

		Log.d(TAG, "RetrieveContacts"); 
		
		String contactNameStr = null;
		String contactNumberStr = null;
		String contactIdStr = null;
		Cursor cursor = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

		Log.d(TAG, "Dopo prima query"); 
		
		totalContacts = 0;
		int contactsWithNumber = 0;
		while (cursor.moveToNext()) {
			totalContacts++;
			contactNameStr  = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)); 
			contactsNameArray.add(contactNameStr);

			contactIdStr = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID)); 
			contactsIdArray.add(contactIdStr);
			if (cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)>0) { 
				contactsWithNumber++;
				// You know it has a number so now query it like this
				Cursor phones = getContentResolver().query( ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, ContactsContract.CommonDataKinds.Phone.CONTACT_ID +" = "+ contactIdStr, null, null); 
				Log.d(TAG, "Dopo seconda query"); 
				while (phones.moveToNext()) { 
					contactNumberStr = phones.getString(phones.getColumnIndex( ContactsContract.CommonDataKinds.Phone.NUMBER)); 
					contactsNumberArray.add(contactNumberStr);
				} 
			}else
				contactsNumberArray.add("No Number");
		}
		Log.d(TAG, "Total contacts: " + totalContacts + " With phone number: " + contactsWithNumber);
		cursor.close();
	}


	public void ContactsGestureHandling(String intAction) {

		if (intAction.equals(GestureIntents.INTENT_GESTURE_SELECT)) {

			if ((counter = list.Movement(intAction)) == -1)
				return;
			onClick_D();
		}

		if (intAction.equals(GestureIntents.INTENT_GESTURE_RIGHT) ||
			intAction.equals(GestureIntents.INTENT_GESTURE_LEFT)){

			if ((counter = list.Movement(intAction)) == -1)
				return;

			name = contactsNameArray.get(counter);
			number = contactsNumberArray.get(counter);
			contactName.setText(name);			
			contactNumber.setText(number);
			speechManager.say(name, true, false);
		} 
	}
}
